from forest.server.api.application import WSGIApplication
from sqlalchemy import create_engine

import webapp2



import os
__PATH__ = os.path.dirname(os.path.abspath(__file__))

import os
import mimetypes
import webapp2
import logging
import yaml

def main(args):
    # TODO: args/config validation
    # TODO: allow manual override

    config = yaml.load(open(args.config).read())
    port = config.get('port')
    name = config.get('name')
    root = config.get('root')

    database = config.get('database')
    database_type = config.get('database_type')
    listen = config.get('listen', '')

    dbpath = os.path.dirname(database)
    if not os.path.exists(dbpath):
        try:

            os.makedirs(dbpath)
        except OSError, e:
            print e.errno
            if e.errno == 13:
                raise

    dburl = '%s:///%s' % (database_type, database)

    engine = create_engine(dburl, echo=True)

    init(engine)

    # run paste reloader
    #import paste.reloader as reloader
    #reloader.install()
    from wsgiref import simple_server

    c = {
        'static_file_path':os.path.join(__PATH__, 'static'),
        'forest_root': os.path.abspath(root),
        'server_name': name
    }
    app = WSGIApplication([
    (r'/static/(.+)', 'forest.server.api.staticfilehandler.StaticFileHandler'),
    (r'/root/(.+)', 'forest.server.handlers.filehandler.FileHandler'),
    webapp2.Route('/', 'forest.server.handlers.home.Home','home'),
    webapp2.Route('/showroot', 'forest.server.handlers.showroot.ShowRoot','show-root'),

    webapp2.Route('/node', 'forest.server.handlers.node.Node','node'),
    webapp2.Route('/get-tree', 'forest.server.handlers.nodes.NodeGetTree','get-tree'),
    webapp2.Route('/node/list', 'forest.server.handlers.nodes.NodeList','nodes'),
    webapp2.Route('/node/new', 'forest.server.handlers.nodes.NodeNew', 'nodes-new'),
    webapp2.Route('/node/<id>', 'forest.server.handlers.nodes.NodeView','node-node'),
    webapp2.Route('/node/<id>/edit', 'forest.server.handlers.nodes.NodeEdit','nodes-edit'),
    webapp2.Route('/settings', 'forest.server.handlers.settings.Settings', 'settings'),
    ], debug=True, engine=engine, config=c)

    simple_server.make_server(listen, port, app).serve_forever()
    #from paste import httpserver
   # httpserver.serve(app, host='127.0.0.1', port='8080')

def init(engine):
    from forest.server.api.db import Base
    from forest.server.models.node import Node
    # TODO: find all other models in models dir so base becomes aware
    metadata = Base.metadata
    metadata.create_all(engine)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config', required=True, help="Config file")
    args = parser.parse_args()
    main(args)
